package com.dhruvtaara.beta.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dhruvtaara.beta.action.LoginAction;
import com.dhruvtaara.beta.toolset.AppLog;
import com.dhruvtaara.beta.toolset.DefaultEncryption;
import com.google.gson.Gson;

public class LoginServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -5092182191252778269L;
	
	/**
	 * 
	 */
	private static final AppLog logger = new AppLog(
			DefaultEncryption.class.getName());

	/**
	 * 
	 */
	public void doGet(
			HttpServletRequest request, 
			HttpServletResponse response
			){
		ServletContext context = getServletContext();
		RequestDispatcher dispatcher = context.getRequestDispatcher("/view/login.jsp");
		try {
			dispatcher.forward(request, response);
		} catch (ServletException e) {
			logger.Error(e.toString());
		} catch (IOException e) {
			logger.Error(e.toString());
		}
	}
	
	/**
	 * 
	 */
	public void doPost(
			HttpServletRequest request, 
			HttpServletResponse response){
		LoginAction loginAction = new LoginAction();
		String emailId = request.getParameter("emailIdField");
		String password = request.getParameter("passwordField");
		boolean successful = loginAction.doLogin(emailId, password);
		response.setContentType("application/json");
		PrintWriter writer;
		try {
			writer = response.getWriter();
			Gson gson = new Gson();
			writer.print(gson.toJson(successful));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
}
